<script>
export default {
    name: "Level"
}
</script>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { User_Level, Maintain_Image } from "@/api";

// 加载等级列表
let levelData = ref([])
let level_list = async () => {
    let { status, msg, data } = await User_Level.level_list();
    if (status === 200) {
        levelData.value = data.list;
    } else {
        ElMessage.error(msg);
    }
}

// 搜索
let searchForm = reactive({
    is_show: '',
    title: '',
})
let handleSelectChange = async (is_show) => {
    let { status, msg, data } = await User_Level.level_list({ is_show });
    if (status === 200) {
        levelData.value = data.list;
    }
}
let handleSearchLevel = async () => {
    let { status, msg, data } = await User_Level.level_list(searchForm);
    if (status === 200) {
        levelData.value = data.list;
    }
}

// 编辑用户等级
let current_index = ref(0)
let edit_level_visible = ref(false)
let editForm = ref({})
let handleEditLevel = (level, index) => {
    current_index.value = index;
    editForm.value = { ...level };
    edit_level_visible.value = true;
}
let handleEditSub = async () => {
    let { status, msg } = await User_Level.level_set(editForm.value);
    if (status === 200) {
        // 操作DOM
        levelData.value[current_index.value] = editForm.value;
        edit_level_visible.value = false;
    } else {
        ElMessage.error(msg);
    }
}

// 开关切换
let handleSwitch = async (item) => {
    let id = item.id;
    let is_show = item.is_show ? 1 : 0;
    let { status, msg } = await User_Level.level_show_hidden(id, is_show);
    if (status === 200) {
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}

// 选择图标
let activeName = ref('')
let iconData = ref([])
let sift_icon = ref('')
let selectedIds = ref([])
let totalIcon = ref([])
let changeImg = ref('')
let select_icon_visible = ref(false)
let editIcon = ref(false)
let handleSelectIcon = async () => {
    editIcon.value = true;
    // 分类列表
    let { status, msg, data } = await Maintain_Image.cate_list();
    // 图标列表
    let { status: iconStatus, data: icon } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
    if (status === 200 && iconStatus === 200) {
        iconData.value = data.list;
        totalIcon.value = icon.list;
        total.value = icon.count;
        select_icon_visible.value = true;
    }
}
let toggleSelection = (item) => {
    if (isSelected(item.att_id)) {
        // 如果已经选中，取消选中并从数组中删除
        let index = selectedIds.value.indexOf(item.att_id)
        if (index !== -1) {
            selectedIds.value.splice(index, 1)
        }
    } else {
        // 如果未选中，添加到数组中
        selectedIds.value.push(item.att_id)
        changeImg.value = item.att_dir;
    }

}
let isSelected = (id) => {
    // 判断 ID 是否在数组中
    return selectedIds.value.includes(id)
}
// 更换图标
let handleChangeImg = () => {
    if (selectedIds.value.length >= 2) {
        ElMessage.error("最多只能选一张图片！");
    } else {
        editForm.value.icon = changeImg.value;
        select_icon_visible.value = false;
    }
}
// 删除图片
let handleRemoveImg = () => {
    ElMessageBox.confirm(
        '确定要删除选中的图片？',
        '删除选中的图片',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let ids = selectedIds.value.toString();
            let { status, msg } = await Maintain_Image.file_del({ ids });
            if (status === 200) {
                let { status, data } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
                if (status === 200) {
                    totalIcon.value = data.list;
                    total.value = data.count;
                    ElMessage.success(msg);
                }
            } else {
                ElMessage.error(msg);
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功',
            })
        })
}

// 选择背景图
let handleSelectImg = async () => { }

// 关闭
let hangleEditIconClose = () => {
    selectedIds.value = [];
    editIcon.value = false;
    addIcon.value = false;
    addImg.value = false;
}


// 分页
let total = ref(0)
let currentPage = ref(1)
let pageSize = ref(18)
let handleCurrentChange = async (page) => {
    let { status, msg, data } = await Maintain_Image.file_list({ pid: pid.value, page: page, limit: 18 });
    if (status) {
        totalIcon.value = data.list;
    }
}

// 分类切换
let pid = ref('')
let handleTabsChange = async (tab) => {
    pid.value = JSON.parse(JSON.stringify(tab.props.name));
    let { status, msg, data } = await Maintain_Image.file_list({ page: 1, limit: 18, pid: pid.value });
    if (status === 200) {
        currentPage.value = 1;
        totalIcon.value = data.list;
        total.value = data.count;
    }
}

// 搜索分类
let search_cate = ref('')
let handleSearchCate = async () => {
    let { status, msg, data } = await Maintain_Image.cate_list({ name: search_cate.value });
    if (status === 200) {
        iconData.value = data.list;
    }
}

// 添加用户等级
let add_level_visible = ref(false)
let addForm = reactive({
    name: '',
    grade: 0,
    discount: 100,
    exp_num: 0,
    icon: '',
    image: '',
    is_show: 0,
})
let addIcon = ref(false)
let handleAddIcon = async () => {
    addIcon.value = true;
    let { status, msg, data } = await Maintain_Image.cate_list();
    let { status: iconStatus, data: icon } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
    if (status === 200 && iconStatus === 200) {
        iconData.value = data.list;
        totalIcon.value = icon.list;
        total.value = icon.count;
        select_icon_visible.value = true;
    }
}
let handleAddFormIcon = () => {
    if (selectedIds.value.length >= 2) {
        ElMessage.error("最多只能选一张图片！");
    } else {
        addForm.icon = changeImg.value;
        select_icon_visible.value = false;
    }
}
let addImg = ref(false)
let handleAddImg = async () => {
    addImg.value = true;
    let { status, data } = await Maintain_Image.cate_list();
    let { status: iconStatus, data: icon } = await Maintain_Image.file_list({ pid: 0, page: 1, limit: 18 });
    if (status === 200 && iconStatus === 200) {
        iconData.value = data.list;
        totalIcon.value = icon.list;
        total.value = icon.count;
        select_icon_visible.value = true;
    }
}
let handleAddFormImg = () => {
    if (selectedIds.value.length >= 2) {
        ElMessage.error("最多只能选一张图片！");
    } else {
        addForm.image = changeImg.value;
        select_icon_visible.value = false;
    }
}
let handleAddForm = async () => {
    let { status, msg } = await User_Level.level_set(addForm);
    if (status === 200) {
        // 操作DOM
        levelData.value.push(addForm);
        level_list();
        add_level_visible.value = false;
    } else {
        ElMessage.error(msg);
    }
}

// 删除
let handleDelLevel = () => {
    ElMessageBox.confirm(
        '确定要删除该等级吗？',
        '删除等级',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let { status, msg } = await User_Level.level_del(item.id);
            if (status === 200) {
                // 操作DOM
                levelData.value.splice(index, 1);
                ElMessage.success(msg);
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除操作！',
            })
        })
}

onMounted(() => {
    level_list();
})
</script>

<template>
    <el-card class="box-card" shadow="never">
        <div class="search-card">
            <el-form :model="searchForm" label-width="120px" class="search-form">
                <el-form-item label="状态：">
                    <el-select v-model="searchForm.is_show" placeholder="请选择" @change="handleSelectChange">
                        <el-option label="全部" value="" />
                        <el-option label="显示" :value="1" />
                        <el-option label="不显示" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="等级名称：">
                    <el-input v-model="searchForm.title">
                        <template #append>
                            <el-button icon="Search" @click="handleSearchLevel" />
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
        </div>
        <div class="add-btn">
            <el-button type="primary" icon="Plus" @click="add_level_visible = true">添加用户等级</el-button>
        </div>
        <div class="user-level">
            <el-table :data="levelData" style="width: 100%" class="levelTable"
                :header-cell-style="{ background: '#f4f3f9', color: '#606266' }">
                <el-table-column prop="id" label="ID" />
                <el-table-column label="等级图标">
                    <template #default="scope">
                        <el-image style="width: 40px;" :src="scope.row.icon" fit="fill" />
                    </template>
                </el-table-column>
                <el-table-column label="等级背景图">
                    <template #default="scope">
                        <el-image style="width: 40px;height: 40px;" :src="scope.row.image" fit="fill" />
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="等级名称" />
                <el-table-column prop="grade" label="等级" />
                <el-table-column prop="discount" label="享受折扣" />
                <el-table-column prop="exp_num" label="经验值要求" />
                <el-table-column label="是否显示">
                    <template #default="scope">
                        <el-switch v-model="scope.row.is_show" :active-value="1" :inactive-value="0" inline-prompt
                            active-text="显示" inactive-text="隐藏" @change="handleSwitch(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-dropdown>
                            <span class="el-dropdown-link">
                                更多
                                <el-icon class="el-icon--right">
                                    <arrow-down />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        @click="handleEditLevel(scope.row, scope.$index)">编辑等级</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleDelLevel(scope.row, scope.$index)">删除等级</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-card>

    <!-- 添加用户等级 -->
    <el-dialog v-model="add_level_visible" title="添加用户等级" width="60%">
        <el-form :model="addForm" label-width="120px">
            <el-form-item label="等级名称">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <div class="form-number">
                <el-form-item label="等级">
                    <el-input-number v-model="addForm.grade" size="small" controls-position="right" />
                </el-form-item>
                <el-form-item label="享受折扣">
                    <el-input-number v-model="addForm.discount" size="small" controls-position="right" />
                </el-form-item>
                <el-form-item label="解锁需经验达到">
                    <el-input-number v-model="addForm.exp_num" size="small" controls-position="right" />
                </el-form-item>
            </div>
            <el-form-item label="图标">
                <el-avatar shape="square" :size="50" :src="addForm.icon" @click="handleAddIcon" />
            </el-form-item>
            <el-form-item label="用户等级背景">
                <el-avatar shape="square" :size="50" :src="addForm.image" @click="handleAddImg" />
            </el-form-item>
            <el-form-item label="是否显示">
                <el-radio-group v-model="addForm.is_show" class="ml-4">
                    <el-radio :label="1" size="large">显示</el-radio>
                    <el-radio :label="0" size="large">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" class="level-btn" @click="handleAddForm">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑用户等级 -->
    <el-dialog v-model="edit_level_visible" title="编辑用户等级" width="60%">
        <el-form :model="editForm" label-width="120px">
            <el-form-item label="等级名称">
                <el-input v-model="editForm.name" />
            </el-form-item>
            <div class="form-number">
                <el-form-item label="等级">
                    <el-input-number v-model="editForm.grade" size="small" controls-position="right" />
                </el-form-item>
                <el-form-item label="享受折扣">
                    <el-input-number v-model="editForm.discount" size="small" controls-position="right" />
                </el-form-item>
                <el-form-item label="解锁需经验达到">
                    <el-input-number v-model="editForm.exp_num" size="small" controls-position="right" />
                </el-form-item>
            </div>
            <el-form-item label="图标">
                <el-avatar shape="square" :size="50" :src="editForm.icon" @click="handleSelectIcon" />
            </el-form-item>
            <el-form-item label="用户等级背景">
                <el-avatar shape="square" :size="50" :src="editForm.image" @click="handleSelectImg" />
            </el-form-item>
            <el-form-item label="是否显示">
                <el-radio-group v-model="editForm.is_show" class="ml-4">
                    <el-radio :label="1" size="large">显示</el-radio>
                    <el-radio :label="0" size="large">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" class="level-btn" @click="handleEditSub">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 选择图标 -->
    <el-dialog v-model="select_icon_visible" title="请选择图标" width="70%" @close="hangleEditIconClose">
        <div class="icon-select">
            <div class="select-cate">
                <el-input v-model="search_cate" placeholder="请输入分类名称" style="width: 200px;margin-bottom: 20px;"
                    class="input-with-select">
                    <template #append>
                        <el-button icon="Search" @click="handleSearchCate" />
                    </template>
                </el-input>
            </div>
            <div>
                <el-button type="primary" :disabled="selectedIds.length ? false : true" @click="handleAddFormImg"
                    v-show="addImg">使用选中图片</el-button>
                <el-button type="primary" :disabled="selectedIds.length ? false : true" @click="handleAddFormIcon"
                    v-show="addIcon">使用选中图片</el-button>
                <el-button type="primary" :disabled="selectedIds.length ? false : true" @click="handleChangeImg"
                    v-show="editIcon">使用选中图片</el-button>
                <el-button type="primary">上传图片</el-button>
                <el-button type="danger" style="margin-right: 15px;" :disabled="selectedIds.length ? false : true"
                    @click="handleRemoveImg">删除图片</el-button>
                <el-select v-model="sift_icon" class="m-2" placeholder="图片移动至">
                    <el-option v-for="item in iconData" :key="item.id" :label="item.title" :value="item.id" />
                </el-select>
            </div>
        </div>
        <el-tabs v-model="activeName" tab-position="left" class="demo-tabs" @tab-click="handleTabsChange">
            <el-tab-pane label="全部图片" name=""></el-tab-pane>
            <el-tab-pane v-for="icon in iconData" :key="icon.id" :label="icon.title" :name="icon.id"></el-tab-pane>
            <div class="total-icons">
                <div v-for="item in totalIcon" @click="toggleSelection(item)" class="only-icon"
                    :class="{ selected: isSelected(item.att_id) }">
                    <el-badge :value="selectedIds.indexOf(item.att_id) >= 0 ? selectedIds.indexOf(item.att_id) + 1 : ''">
                        <el-image style="width: 100px; height: 100px" :src="item.satt_dir" fit="fill"
                            :title="item.real_name" />
                    </el-badge>
                    <div class="img-title">{{ item.real_name }}</div>
                </div>
            </div>
        </el-tabs>
        <div class="icon-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                layout="total, prev, pager, next, jumper" :total="total" @current-change="handleCurrentChange" />
        </div>
    </el-dialog>
</template>

<style lang="less" scoped>
.box-card {
    .search-card {
        margin-bottom: 20px;

        .search-form {
            display: flex;
            justify-content: flex-start;
        }
    }

    .add-btn {
        margin-bottom: 20px;
    }

    .user-level {
        .levelTable {
            .el-dropdown-link {
                cursor: pointer;
                color: var(--el-color-primary);
                display: flex;
                align-items: center;

                &:focus {
                    outline: none;
                }
            }
        }
    }
}

.form-number {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.level-btn {
    width: 100%;
}

.icon-select {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

}

.demo-tabs {

    .total-icons {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;

        .only-icon {
            width: 100px;
            border: 2px solid transparent;
            margin: 5px 20px 5px 20px;

            .img-title {
                font-size: 10px;
                text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }

        .selected {
            border-width: 2px;
            border-color: #5fb878;
        }
    }
}

.icon-page {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>